package com.example.project.framework;

import com.example.project.action.ActionParam;
import com.example.project.action.ActionUtil;
import com.example.project.util.IntegerUtil;
import com.example.project.util.StringUtil;
import com.github.pagehelper.PageHelper;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 统一请求拦截器，在这里进行一些基础框架数据的处理。。。。
 *
 * @author Chenth
 */
public class DataInterceptor extends BaseController implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestUrl = request.getRequestURI().replaceFirst(request.getContextPath(), "");
        logger.info(StringUtil.join("**********************REQUEST-URL:", requestUrl, "***********************"));
        logger.info(StringUtil.join("**********************BASE:", request.getScheme(), "://", request.getServerName(), ":", request.getServerPort(), request.getContextPath(), "/***********************"));
        logger.info(StringUtil.join("**********************IP-ADRESS:", (request.getHeader("X-Real-IP") == null ? request.getRemoteAddr() : request.getHeader("X-Real-IP")), ",SessionID:", request.getSession().getId()));
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Access-Control-Allow-Origin", "*");
        /**
         * 如果登录客户端类型没有设置或者为Web端
         */

        ActionParam p = new ActionParam();
        p.setParam(getParamFromRequest(request));
        ActionUtil.setActionParam(p);
        setPaginationInfo(request);
        return true;
    }

    /**
     * 将请求里面的所有参数设置到Param中
     *
     * @return
     */
    private HashMap<String, String> getParamFromRequest(HttpServletRequest request) {
        HashMap<String, String> param = new HashMap<>();
        Map<?, ?> map = request.getParameterMap();
        for (Object key : map.keySet()) {
            logger.info("Param:{}={}", key.toString(),request.getParameter(key.toString()));
            param.put(key.toString(), request.getParameter(key.toString()));
        }
//        ShiroCacheObj obj = currAdminInfo();
//        param.put("createBy",obj.getUserName());
//        param.put("updateBy",obj.getUserName());
        return param;
    }


    /**
     * 将分页参数设置到线程中
     *
     * @param request
     */
    private void setPaginationInfo(HttpServletRequest request) {
        Integer page = StringUtil.isEmpty(request.getParameter("pageNo"))?0:IntegerUtil.getValue(request.getParameter("pageNo"));
        Integer limit = StringUtil.isEmpty(request.getParameter("pageSize")) ? 1000 : Integer.parseInt(request.getParameter("pageSize"));
        ActionUtil.getActionParam().setStart((page-1)*limit);
        ActionUtil.getActionParam().setLimit(limit);
        PageHelper.startPage(ActionUtil.getStart(),ActionUtil.getLimit());
    }

    @Override
    public void afterCompletion(HttpServletRequest arg0,
                                HttpServletResponse arg1, Object arg2, Exception arg3)
            throws Exception {
        // TODO Auto-generated method stub

    }

    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
                           Object arg2, ModelAndView arg3) throws Exception {
        // TODO Auto-generated method stub

    }
}
